#!/usr/bin/env python
# -*- coding: utf-8 -*-
from core.ide.datamangager import DataMangager
import socket
import threading

SIZE=4

HOST=DataMangager().getData("Druid","Socket Server","127.0.0.1",None,"Socket")
PORT=DataMangager().getData("Druid","Socket Port",5432,None,"Socket")

class Comunicator:
    def __init__(self):
        self._result=""
    
    def start(self):
        self._sender = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self._sender.connect((HOST,PORT))
        self._sender.send('$SEND') # telling server we will send data from here
        
        self._reciever = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self._reciever.connect((HOST,PORT))
        self._reciever.send('$RECV') # telling server we will recieve data from here
        self.tread=RecvTread(self._reciever)
    
    def stop(self):
        pass
    

    def send(self,cmd,callback):
        self._callback=callback
        self._send(cmd)
    
    def _send(self,cmd):
        if len(cmd)<=999 and len(cmd)>0:
            self._sender.send(str(len(cmd)))
            if self._sender.recv(2) == 'OK':
                self._sender.send(cmd)
        else:
            self._sender.send(str(999))
            if self._sender.recv(2) == 'OK':
                self._sender.send(cmd[:999])
                msend(self._sender,cmd[1000:])
                
    def _recv(self,result):
        if result!="__$end__":
            self._result+=result
        else:
            self._callback(self._result)
            self._result=""

class RecvTread(threading.Thread):
    def __init__(self, reciever,callback):
        threading.Thread.__init__(self)
        self._reciever = reciever
        self._callback=callback
        self.stopIt = False

    def mrecv(self):
        data = self.conn.recv(SIZE)
        self.conn.send('OK')
        return self.conn.recv(int(data))

    def run(self):
        while not self.stopIt:
            result = self.mrecv()
            self._callback(result)
            
PyComunicator=Comunicator()
PyComunicator.start()